package com.hitown.util;

import com.hitown.dao.system.SystemLogDao;
import com.hitown.model.system.SystemLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;



/**
 * 系统日志工具类
 * @author cxs
 *
 */
@Component
@Order(value=1)
public class ServerCallLoginLogUtil implements CommandLineRunner {
	
	@Autowired
	SystemLogDao systemLogDao;
	
	private static Logger logger = LoggerFactory.getLogger(ServerCallLoginLogUtil.class);
	private static BlockingQueue<SystemLog> queueLogin =  new LinkedBlockingQueue<SystemLog>();
	
	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub
		//开启一个线程 意思就是不会因为SaveLog类里面的run方法失败而阻塞   会接着往下走
		new Thread(new SaveLoginLog()).start();
	}

	public static void put(SystemLog paramMap) {
		try {
			queueLogin.put(paramMap);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
//  当传入参数时执行
	private class SaveLoginLog implements Runnable {

		@Override
		public void run() {
			while (true) {
				try {
					while(true){
						SystemLog log = queueLogin.take();
						systemLogDao.saveSystemLog(log);
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("{}", e.getMessage());
				}
			}

		}
	}

}
